import { getDatabase } from '../db/index'
import { getLogger } from '../logger/index'

interface ReleaseRecordInput {
  dateYMD: string
  office_code?: string
  service_type?: string
  reason?: string
  range_start?: string
  range_end?: string
  monitor_id?: number
  extra?: any
}

class ReleaseRecordService {
  private ensured = false
  private logger = getLogger()
  private get prisma() { return getDatabase() as any }

  private async ensureTable(): Promise<void> {
    if (this.ensured)
      return
    try {
      await this.prisma.$executeRawUnsafe(`
        CREATE TABLE IF NOT EXISTS release_record (
          id INTEGER PRIMARY KEY AUTOINCREMENT,
          date TEXT NOT NULL,
          office_code TEXT,
          service_type TEXT,
          reason TEXT,
          range_start TEXT,
          range_end TEXT,
          monitor_id INTEGER,
          created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
          extra TEXT
        );
      `)
      await this.prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_release_record_date ON release_record(date);`)
      await this.prisma.$executeRawUnsafe(`CREATE INDEX IF NOT EXISTS idx_release_record_created_at ON release_record(created_at);`)
      this.ensured = true
    }
    catch (e) {
      this.logger.warn('确保 release_record 表失败', { error: (e as any)?.message || String(e) })
    }
  }

  async record(input: ReleaseRecordInput): Promise<void> {
    try {
      await this.ensureTable()
      const extraStr = input.extra ? JSON.stringify(input.extra) : null
      await this.prisma.$executeRawUnsafe(
        `INSERT INTO release_record (date, office_code, service_type, reason, range_start, range_end, monitor_id, extra) VALUES (?, ?, ?, ?, ?, ?, ?, ?);`,
        input.dateYMD,
        input.office_code || null,
        input.service_type || null,
        input.reason || null,
        input.range_start || null,
        input.range_end || null,
        typeof input.monitor_id === 'number' ? input.monitor_id : null,
        extraStr,
      )
    }
    catch (e) {
      this.logger.warn('写入放号记录失败', { error: (e as any)?.message || String(e), payload: input })
    }
  }
}

let svc: ReleaseRecordService | null = null
export function getReleaseRecordService(): ReleaseRecordService {
  if (!svc)
    svc = new ReleaseRecordService()
  return svc
}
